﻿using EggLink.DanhengServer.Data;
using EggLink.DanhengServer.Internationalization;
using EggLink.DanhengServer.Proto;
using EggLink.DanhengServer.Util;
using Google.Protobuf;
using Newtonsoft.Json;

namespace EggLink.DanhengServer.WebServer.Handler;

/// <summary>
/// 处理网关查询请求的处理程序
/// 负责构建并返回网关服务器信息
/// </summary>
internal class QueryGatewayHandler
{
    public static Logger Logger = new("GatewayServer");
    public string Data { get; }

    /// <summary>
    /// 初始化网关查询处理程序
    /// 根据配置构建网关服务器信息并转换为Base64格式
    /// </summary>
    public QueryGatewayHandler ()
    {
        var config = ConfigManager.Config;
        var urlData = config.DownloadUrl;

        Logger.Info("开始构建网关服务器信息...");
        Logger.Debug($"服务器配置: {JsonConvert.SerializeObject(config.GameServer)}");
        Logger.Debug($"下载URL配置: {JsonConvert.SerializeObject(urlData)}");

        // 构建网关协议对象
        var gateServer = new GateServer
        {
            RegionName = config.GameServer.GameServerId,
            Ip = config.GameServer.PublicAddress,
            Port = config.GameServer.Port,
            Msg = I18NManager.Translate("Server.Web.Maintain"),
            EnableVersionUpdate = true,
            EnableUploadBattleLog = true,
            EnableWatermark = true,
            PILJCFDPOPM = true,
            EnableAndroidMiddlePackage = true,
            NetworkDiagnostic = true,
            CloseRedeemCode = true
        };

        Logger.Info("基础网关信息已设置");

        // 如果启用数据包加密，添加客户端密钥
        if (ConfigManager.Config.GameServer.UsePacketEncryption)
        {
            gateServer.ClientSecretKey = Convert.ToBase64String(Crypto.ClientSecretKey!.GetBytes());
            Logger.Info("已添加客户端加密密钥");
        }

        // 检查资源是否加载完成
        if (!ResourceManager.IsLoaded)
        {
            gateServer.Retcode = 2;
            Logger.Warn("资源未加载完成，设置返回码为2");
        }

        // 设置各种资源URL
        SetResourceUrl(gateServer, urlData.AssetBundleUrl, nameof(gateServer.AssetBundleUrl));
        SetResourceUrl(gateServer, urlData.ExResourceUrl, nameof(gateServer.ExResourceUrl));
        SetLuaUrl(gateServer, urlData.LuaUrl);
        SetIfixUrl(gateServer, urlData.IfixUrl);

        Logger.Info("网关信息构建完成");
        Logger.Debug($"网关协议对象: {JsonConvert.SerializeObject(gateServer)}");

        Data = Convert.ToBase64String(gateServer.ToByteArray());
        Logger.Info($"网关信息已转换为Base64: {Data}");
    }

    /// <summary>
    /// 设置资源URL
    /// </summary>
    /// <param name="gateServer">网关服务器对象</param>
    /// <param name="url">资源URL</param>
    /// <param name="propertyName">属性名称</param>
    private void SetResourceUrl (GateServer gateServer, string? url, string propertyName)
    {
        if (!string.IsNullOrEmpty(url))
        {
            typeof(GateServer).GetProperty(propertyName)?.SetValue(gateServer, url);
            Logger.Info($"已设置{propertyName}: {url}");
        }
    }

    /// <summary>
    /// 设置Lua资源URL和版本
    /// </summary>
    /// <param name="gateServer">网关服务器对象</param>
    /// <param name="url">Lua资源URL</param>
    private void SetLuaUrl (GateServer gateServer, string? url)
    {
        if (!string.IsNullOrEmpty(url))
        {
            gateServer.LuaUrl = url;
            gateServer.MdkResVersion = url.Split('/')[^1].Split('_')[1];
            Logger.Info($"已设置Lua资源URL: {url}, 版本: {gateServer.MdkResVersion}");
        }
    }

    /// <summary>
    /// 设置Ifix资源URL和版本
    /// </summary>
    /// <param name="gateServer">网关服务器对象</param>
    /// <param name="url">Ifix资源URL</param>
    private void SetIfixUrl (GateServer gateServer, string? url)
    {
        if (!string.IsNullOrEmpty(url))
        {
            gateServer.IfixUrl = url;
            gateServer.IfixVersion = url.Split('/')[^1].Split('_')[1];
            Logger.Info($"已设置Ifix资源URL: {url}, 版本: {gateServer.IfixVersion}");
        }
    }
}